package com.badlogic.androidgames.framework.impl;

import java.io.IOException;

import com.badlogic.androidgames.framework.Music;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

/**
 * @deprecated:音乐(适合时间较长的音频)
 * @author frank
 * @date 2015年11月30日
 */
public class AndroidMusic implements Music, OnCompletionListener {
	/**音乐播放器**/
	MediaPlayer mediaPlayer;
	/**是否准备好	Prepared 准备**/
	boolean isPrepared = false;
	
	public AndroidMusic(AssetFileDescriptor assetFileDescriptor) {	// AssetFileDescriptor 资源文件描述
		mediaPlayer = new MediaPlayer();
		try {
			/**DataSource 数据源	Offset 偏移量**/
			mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(),
					assetFileDescriptor.getLength());
			mediaPlayer.prepare();	// 准备
			isPrepared = true;
			mediaPlayer.setOnCompletionListener(this);	// 完成监听器
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**播放**/
	@Override
	public void play() {
		if (mediaPlayer.isPlaying())
			return;
		try {
			synchronized (this) {
				if(!isPrepared)
					mediaPlayer.prepare();
				mediaPlayer.start();
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**停止**/
	@Override
	public void stop() {
		mediaPlayer.stop();
		synchronized (this) {
			isPrepared = false;
		}
	}
	/**暂停**/
	@Override
	public void pause() {
		if (mediaPlayer.isPlaying())
			mediaPlayer.pause();
	}
	/**循环**/
	@Override
	public void setLooping(boolean looping) {
		mediaPlayer.setLooping(looping);
	}
	/**音量**/
	@Override
	public void setVolume(float volume) {
		mediaPlayer.setVolume(volume, volume);
	}
	/**是否在播放**/
	@Override
	public boolean isPlaying() {
		return mediaPlayer.isPlaying();
	}
	/**是否停止**/
	@Override
	public boolean isStopped() {
		return !isPrepared;
	}
	/**是否循环**/
	@Override
	public boolean isLooping() {
		return mediaPlayer.isLooping();
	}
	/**处理**/
	@Override
	public void dispose() {
		if (mediaPlayer.isPlaying())
			mediaPlayer.stop();
		mediaPlayer.release();	// 释放
	}
	/**完成**/
	@Override
	public void onCompletion(MediaPlayer player) {
		synchronized (this) {
			isPrepared = false;
		}
	}
	
}
